using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using PetShop.Web.Controls;
using PetShop.Web.Entities;
using PetShop.Web.WebComponents;

namespace PetShop.Web
{
    public partial class ItemDetails : Page
    {
        protected NavBar header;
        protected ItemInfo itemInfo;

        private void InitializeComponent()
        {
        }


        protected override void OnLoad(EventArgs e)
        {
            string itemId = CleanString.InputText(Request["itemId"], 50);


            ItemInfo item = null;

            using (var cmd = new SqlCommand())
            {
                using (var conn = new SqlConnection(ConfigurationManager.AppSettings["SQLConnString"]))
                {
                    cmd.Connection = conn;
                    cmd.CommandText =
                        "SELECT Item.ItemId, Item.description, Item.InventoryQty, Item.ListPrice, Product.Name, Product.Descn FROM Item  INNER JOIN Product ON Item.ProductId = Product.ProductId WHERE Item.ItemId = @ItemId";
                    cmd.CommandType = CommandType.Text;
                    var parm = new SqlParameter("@ItemId", SqlDbType.VarChar, 10);
                    parm.Value = itemId;
                    cmd.Parameters.Add(parm);
                    conn.Open();
                    using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                    {
                        rdr.Read();
                        item = new ItemInfo(rdr.GetString(0).Trim(), rdr.GetString(1), rdr.GetInt32(2),
                                            rdr.GetDecimal(3), rdr.GetString(4), rdr.GetString(5));
                        itemInfo = item;
                    }
                }
            }


            if (itemInfo != null)
            {
                lblDescription.Text = itemInfo.ProductDesc;
                lblName.Text = itemInfo.Name;
                lblProductName.Text = itemInfo.ProductName;
                lblPrice.Text = itemInfo.Price.ToString("c");


                if (itemInfo.Quantity > 0)
                    lblQty.Text = itemInfo.Quantity.ToString();
                else
                {
                    lblQty.Text = "Back Ordered";
                    lblQty.CssClass = "alert";
                }
            }
            else
            {
                lblSearchResults.Text = "Item not found";
            }
        }
    }
}